import { Injectable,HttpException, HttpStatus  } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from '../entity';
import { Repository,EntityRepository } from 'typeorm';
import { UserCreateDto } from './dto/user.login.dto';
import { AppError } from '../error/index';
import { generateId, generateToken } from '../util';
import rp = require('request-promise');
@Injectable()
export class UserService {
  constructor(

    @InjectRepository(User)
    private readonly userRepository: Repository<User>

    ) { }
  
  async findOne(userId: string): Promise<User> {
    const result = await this.userRepository.findOne({ userId });
    if (result) {
      delete result.password;
      return result;
    }
    throw new AppError('用户不存在', 20);
  }

  async create(user): Promise<any>{
    const { username } = user;
    const result = await this.userRepository.count({ username });
    if (result) {
      throw new AppError('名称已存在', 20);
    }
    const res = await this.userRepository.save(user);
    delete res.password;
    return res;
  }

  async login(body): Promise<any>{
    const { username,password} = body;
    const user = await this.userRepository.findOne({ username });
    if(!user){throw new AppError('用户名不正确',20)}
    const pass = await this.userRepository.findOne({ password });
    if(!pass){throw new AppError('密码不正确',20)}
    user.token = generateToken();
    const res = await this.userRepository.save(user);
    delete res.password;
    return res;
  }

  async getOpenID(body) {//用户唯一标识 OpenID 和 会话密钥 session_key
    const { code } = body;
    try {
      const options = {
        method: 'GET',
        url: 'https://api.weixin.qq.com/sns/jscode2session',
        qs: {
          grant_type: 'authorization_code',
          js_code: code,
          secret: "你的 weixin.secret",
          appid: "wx59f4e88b9f055e6a"
        }
      };
      let sessionData = await rp(options);
      sessionData = JSON.parse(sessionData);
      if (!sessionData.openid) {
        return null;
      }
      return sessionData.openid;

    } catch (e) {
      return null;
    }
  }


// // 创建的方法
// async create(createCatDto: CreateCatDto): Promise<CatEntity> {
//   return await this.catRepository.save(createCatDto);
// }
//   // 查找一条数据
// async findOne(id: number): Promise<CatEntity> {
//   return await this.catRepository.findOne({ id });
//   }
  
//   // 查询全部数据
// async findAll(): Promise<CatEntity[]> {
//   return await this.catRepository.find();
// }

  //原生语句使用
// async findAll(): Promise<CatEntity[]> {
//   return await this.catRepository.query('select * from cat');
// }
  
  // 查询全部数据 使用createQueryBuilder
// async findAll(): Promise<CatEntity[]> {
//   return await this.catRepository
//     .createQueryBuilder('cat') // 查询表名
//     .offset(1) // 从多少条开始
//     .limit(2) // 查询2条数据
//     .orderBy('age', 'DESC') // 排序
//     .getMany(); // 返回多条数据
// }

}